package com.spark.gaea.mvc.config;

import com.google.common.collect.Lists;
import com.spark.gaea.mvc.utils.CustomWebBindingInitializer;
import com.spark.gaea.utils.json.JsonUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import java.util.List;

@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
	@Override
	public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
		converters.add((HttpMessageConverter<?>) this.mappingJackson2HttpMessageConverter());
	}

	@Bean
	public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
		final List<HttpMessageConverter<?>> httpMessageConverterList = Lists.newArrayList();
		httpMessageConverterList.add((HttpMessageConverter<?>) this.mappingJackson2HttpMessageConverter());
		final RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter();
		adapter.setMessageConverters(httpMessageConverterList);
		adapter.setWebBindingInitializer(new CustomWebBindingInitializer());
		return adapter;
	}

	@Bean
	public HttpMessageConverter mappingJackson2HttpMessageConverter() {
		final MappingJackson2HttpMessageConverter httpMessageConverter = new MappingJackson2HttpMessageConverter();
		httpMessageConverter.setObjectMapper(JsonUtil.getMapper());
		return httpMessageConverter;
	}
}
